package com.reggie.setmeal.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.reggie.configuration.common.Result;
import com.reggie.dish.entity.dtos.DishDTO;
import com.reggie.setmeal.entity.Setmeal;
import com.reggie.setmeal.entity.dto.SetmealDTO;
import com.reggie.setmeal.service.SetmealDishService;
import com.reggie.setmeal.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @CacheEvict(value = "setmealCache",allEntries = true)
    @PostMapping
    public Result<String> insertSetmeal(@RequestBody SetmealDTO dto) {
        log.info("套餐信息为:{}", dto);
        setmealService.saveWithDish(dto);
        return Result.success("添加成功");
    }

    /**
     * 套餐管理分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("page")
    public Result<IPage> selectByPage(int page, int pageSize, String name) {
        Result<IPage> iPageResult = setmealService.selectByPage(page, pageSize, name);
        return iPageResult;
    }

    /**
     * 对修改套餐信息进行数据回显
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public Result<SetmealDTO> setSetmeal(@PathVariable("id") Long id) {
        SetmealDTO dto = setmealService.selectByID(id);
        return Result.success(dto);
    }

    /**
     * 删除套餐信息
     *
     * @param ids
     * @return
     *
     * allEntries这个属性是指调用这个方法以后会删除所有缓存数据
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @DeleteMapping
    public Result<String> deleteByIDs(String ids) {
        log.info("要删除的ID为:{}", ids);
        List<Long> LongIDs = new ArrayList<>();
        if (ids.lastIndexOf(",") > 0) {
            String[] split = ids.split(",");
            for (int i = 0; i < split.length; i++) {
                LongIDs.add(Long.parseLong(split[i]));
            }
        } else {
            LongIDs.add(Long.parseLong(ids));
        }
        setmealService.deleteByIDs(LongIDs);
        return Result.success("删除成功");
    }

    /**
     * 对套餐进行停售启售操作
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> stopSellDish(@PathVariable int status, String ids) {
        List<Long> LongIDs = new ArrayList<>();
        if (ids.lastIndexOf(",") > 0) {
            String[] split = ids.split(",");
            for (int i = 0; i < split.length; i++) {
                LongIDs.add(Long.parseLong(split[i]));
            }
        } else {
            LongIDs.add(Long.parseLong(ids));
        }

        setmealService.stopSellSetmeal(status, LongIDs);
        return Result.success("操作成功");
    }

    /**
     * 修改套餐信息
     *
     * @param dto
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PutMapping
    @Transactional
    public Result<String> updateSetmeal(@RequestBody SetmealDTO dto) {
        log.info("套餐信息为:{}", dto);
        //将原有套餐绑定菜品信息进行删除（先使用逻辑删除进行测试，如果影响其他功能就使用真删）
        setmealDishService.deleteByID(dto.getId());
        //将信息重新储存过来
        setmealService.saveWithDish(dto);
        return Result.success("修改成功");
    }


    //这个注解相当于将方法的返回值存入Redis数据库中，相当于一个Hash的属性，Value是大Key， key是小Key
    @CachePut(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status",condition = "#result != null")
    @GetMapping("/list")
    public Result<List<Setmeal>> selectByPage(Setmeal setmeal) {
        log.info("分类的ID为{}",setmeal.getCategoryId());
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);
        return Result.success(list);
    }

}
